<template>
  <el-dialog v-model="dialogInfo.visible" :title="dialogInfo.title" :width="dialogInfo.width" align-center>
    <el-form ref="formRef" label-position="left"  :model="form" :rules="formRules" label-width="120px">
      <el-row>
        <el-col :sm="12">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formModel.title" />
          </el-form-item>
        </el-col>
        <el-col :sm="12">
          <el-form-item label="代码" prop="code">
            <el-input v-model="formModel.code" />
          </el-form-item>
        </el-col>
        <el-col :sm="12">
          <el-form-item label="分组" prop="group_id">
            <el-tree-select v-model="formModel.group_id" :data="optionsOfGroups" :render-after-expand="false"
              style="width:100%" node-key="id" :props="{ children: 'children', label: 'title', }" />
          </el-form-item>
        </el-col>
        <el-col :sm="12">
          <el-form-item label="提示消息" prop="tip">
            <el-input v-model="formModel.tip" />
          </el-form-item>
        </el-col>
        <el-col :sm="12">
          <el-form-item label="值" prop="value">
            <el-input v-model="formModel.value" />
          </el-form-item>
        </el-col>
        <el-col :sm="12">
          <el-form-item label="组件类型" prop="component_name">
            <el-select v-model="formModel.component_name" placeholder="选择组件类型">
              <el-option :label="text" :value="value" v-for="(text, value) of optionsOfComponents" :key="value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :sm="12">
          <el-form-item label="组件数据" prop="component_dataset">
            <el-input v-model="formModel.component_dataset" />
          </el-form-item>
        </el-col>
        <el-col :sm="12">
          <el-form-item label="默认值" prop="default_value">
            <el-input v-model="formModel.default_value" />
          </el-form-item>
        </el-col>
        <el-col :sm="12">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="formModel.sort" />
          </el-form-item>
        </el-col>
        <el-col :sm="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formModel.status" placeholder="选择状态">
              <el-option :label="text" :value="value" v-for="(text, value) of optionsOfStatus" :key="value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onCancel()">取消</el-button>
        <el-button type="info" @click="onReset()">重置</el-button>
        <el-button type="primary" @click="onSubmit()">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 管理员编辑组件
 */
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';

// ======================================================
//                      变量声明
// ======================================================

// emit
const emit = defineEmits(['success']);
// 表单数据
const formAttrs = {
  id: 0,
  title: '',
  code: '',
  group_id: 0,
  tip: '',
  value: '',
  component_name: '',
  component_dataset: '',
  default_value: '',
  status: 1,
};
const formModel =  ref(Object.assign({}, formAttrs));
// 弹窗信息
const dialogInfo = ref({
  visible: false,
  title: '',
  width: '800px',
})
// 表单组件的引用实例
const formRef = ref(null);
// 状态选项数据
const optionsOfStatus = ref({});
// 组件类型选项数据
const optionsOfComponents = ref({});
// 分组选项数据
const optionsOfGroups = ref([]);
// 表单校验规则
const formRules = ref({
  title: [
    { required: true, message: '请填写标题', trigger: 'blur' },
    { min: 3, max: 50, message: '标题长度 3 - 50', trigger: 'blur' }
  ],
  group_id: [
    { required: true, message: '请选择分组', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'blur' }
  ]
})

// ======================================================
//                      点击操作
// ======================================================

// 点击提交按钮
const onSubmit = () => {
  console.log('submit!', formModel.value);
  formRef.value.validate((valid, fields) => {
    if (!valid) {
      console.log('表单校验失败：', fields);
      return;
    }
    let url = formModel.value.id > 0 ? ApiUrls.systemConfigUpdate : ApiUrls.systemConfigSave;
    EsAjax.post(url, formModel.value).then(res => {
      if (res.data.code != 200) {
        ElMessage.warning(res.data.data+res.data.msg);
        return;
      }
      dialogInfo.value.visible = false;
      emit('success');
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    })
  })
}

// 点击重置表单按钮
const onReset = () => {
  ElMessageBox.confirm('确定要重置表单数据吗？').then(() => {
    formRef.value.resetFields();
  }).catch(() => { })
}

// 点击取消按钮
const onCancel = () => {
  dialogInfo.value.visible = false;
}

// ======================================================
//                      处理事件
// ======================================================

// 加载数据
const show = (id, title, width = '800px') => {
  dialogInfo.value.title = title;
  dialogInfo.value.width = width;
  dialogInfo.value.visible = true;

  // 加载分组选项数据
  EsAjax.get(ApiUrls.systemConfigGroupIndex).then(res => {
    if (res.data.code != 200) {
      ElMessage.warning(res.data.data+res.data.msg);
      return;
    }
    optionsOfGroups.value = res.data.data;
  }).catch(err => { ElMessage.error('网络错误：' + err.message) })

  // 加载选项数据
  EsAjax.get(ApiUrls.systemConfigOption).then(res => {
    if (res.data.code != 200) {
      ElMessage.warning(res.data.data+res.data.msg);
      return;
    }
    optionsOfComponents.value = res.data.data.options_of_component;
    optionsOfStatus.value = res.data.data.options_of_status;
  }).catch(err => { ElMessage.error('网络错误：' + err.message) })

  // 加载详情数据
  if (id > 0) {
    EsAjax.get(ApiUrls.systemConfigRead, { params: { id: id } }).then(res => {
      if (res.data.code != 200) {
        ElMessage.warning(res.data.data+res.data.msg);
        return;
      }
      formModel.value = res.data.data ?? Object.assign({}, formAttrs);
    }).catch(err => { ElMessage.error('网络错误：' + err.message) })
  }
}

defineExpose({
  show
})
</script>

<style scoped>

</style>
